package com.sat.client.fragment

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.findNavController
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.sat.client.R
import com.sat.client.adapter.DevicesAdapter
import com.sat.client.app.GlobalData.fileItem
import com.sat.client.databinding.FragmentMainBinding
import com.sat.client.utils.WebSocketManager
import com.sat.client.vm.MainFragmentVM
import com.sat.common.base.BaseFragment
import com.sat.common.base.NoViewModel

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [MainFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class MainFragment : BaseFragment<MainFragmentVM, FragmentMainBinding>() {
    private val devicesAdapter by lazy {
        DevicesAdapter()
    }

    override fun layoutId(): Int {

        return R.layout.fragment_main
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        mBinding?.run {
            rvList.run {
                layoutManager = LinearLayoutManager(requireContext())
                devicesAdapter.addOnItemChildClickListener(R.id.tv_enter) { adapter, view, position ->
                    val item = adapter.getItem(position)
                    item?.run {
                        findNavController().navigate(R.id.action_mainFragment_to_screenFragment)
//                        viewModel.getFiles(ip, httpPort)
                    }

                }
                adapter = devicesAdapter
            }
            refreshLayout.setOnRefreshListener {
                viewModel.scanDevices()

            }

        }
        viewModel.deviceInfos.observe(viewLifecycleOwner) {
            devicesAdapter.submitList(it)
            mBinding?.refreshLayout?.finishRefresh()
        }
        viewModel.fileItem.observe(viewLifecycleOwner) {

            fileItem = it
            findNavController().navigate(R.id.action_mainFragment_to_filesFragment)
        }

    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        viewModel.scanDevices()
    }

}